package com.example.test.netty.encode;

import com.example.test.netty.message.MessageEntity;
import com.example.test.netty.utils.FormatTransferUtils;
import com.example.test.netty.utils.HexUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @program: test
 * @description: 消息编码器
 * @author: qiu bo yang
 * @create: 2020-10-13 14:43
 **/
@Slf4j
@Component
public class MessageEncoder extends MessageToByteEncoder<Object> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        MessageEntity messageEntity = (MessageEntity) o;
        String magic = HexUtils.strToHexStr(messageEntity.getMagic());
        String version = HexUtils.intHex2(messageEntity.getVersion());
        String msgType = HexUtils.intHex2(messageEntity.getMsgType());
        String dataType = HexUtils.intHex2(messageEntity.getDataType());
        String resv = HexUtils.intHex2(messageEntity.getResv());
        String timestamp = HexUtils.byteToHexStr(FormatTransferUtils.toLH(messageEntity.getTimestamp()));
        String squence = HexUtils.byteToHexStr(FormatTransferUtils.toLH(messageEntity.getSquence()));
        String msgBody = HexUtils.strToHexStr(messageEntity.getMsgBody());
        String dataSize = HexUtils.byteToHexStr(FormatTransferUtils.toLH(msgBody.length() / 2));
        String responseStr = magic + version + msgType + dataType + resv + timestamp + squence + dataSize + msgBody;
        //log.info("对象：{},回应信息：{}", messageEntity, responseStr);
        byte[] bytes = HexUtils.hexStrToBytes(responseStr);
        byteBuf.writeBytes(bytes);
    }
}
